/*
 * FeedSet.java
 *
 * Created on July 28, 2007, 1:44 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.afaker.rss.feed;

import com.afaker.rss.*;
import com.afaker.rss.feed.biz.FeedFetcher;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

/**
 *
 * @author bruce
 */
/**Collection-oriented*/
public class FeedSet {
    private LinkedList set;
    private EntrySet entries;
    private final int SLEEP_PERIOD=1000000;
    /** Creates a new instance of FeedSet */
    public FeedSet() {
        set=new LinkedList();
    }
    
    public int size() {
        return set.size();
    }
    
    public boolean isEmpty() {
        return set.isEmpty();
    }
    
    public boolean contains(FeedFetcher o) {
        return false;
    }
    
    public Iterator<FeedFetcher> iterator() {
        return set.iterator();
    }
    public FeedFetcher getFeed(int index){
        return (FeedFetcher) set.get(index);
    }
    
    public boolean addFeed(FeedFetcher e) {
        return set.add(e);
    }
    
    public boolean remove(FeedFetcher o) {
        return set.remove(o);
    }
    
    public boolean addAll(Collection<? extends FeedFetcher> c) {
        return set.addAll(c);
    }
    
    
    public boolean removeAll(Collection<?> c) {
        return set.removeAll(c);
    }
    
    public void clear() {
        set.clear();
    }
    
    synchronized public void refreshAll() {
        Set expiring = new HashSet();
        Iterator iterator = set.iterator();
        FeedFetcher feed;
        if(size() == 0) {
            sleep();
        } else{
            while (iterator.hasNext()) {
                feed = (FeedFetcher) iterator.next();
                System.out.println("Checking: " + feed.getURIString());
                if(feed.refresh())
                    entries = feed.getNewEntries();
                if(feed.shouldExpire()){
                    expiring.add(feed);
                }
            }
            sleep();
        }
        iterator = expiring.iterator();
        while (iterator.hasNext()) {
            feed = (FeedFetcher) iterator.next();
            System.out.println("Unsubscribing from "+feed.getURIString());
            set.remove(feed);
        }
    }
    
    public EntrySet getNewEntry() {
        return entries;
    }
    
    private void sleep() {
        try {
            Thread.sleep(SLEEP_PERIOD);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}
